package com.share.example.wechat.web.wechat;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.share.common.common.Result;
import io.swagger.annotations.ApiImplicitParam;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * java实现PC网站实现微信扫码登陆
 */
@Slf4j
@Controller
public class OpenController {
    private final String WX_CALL_PATH = "/wx/callback";
    @Value("${weixin.open.appId}")
    private String appId;
    @Value("${weixin.open.appSecret}")
    private String appSecret;
    @Value("${rootUrl.weChat}")
    private String weChatRootUrl;

    @Autowired
    private WxMaService wxMaService;

    @ApiImplicitParam("生成一个扫码链接地址---前端把地址变为二维码图片---用户微信扫码后重定向到下面的接口并携带code")
    @RequestMapping("/gen/qrcode/link")
    public Result genQrcodeLink() {
        try {
            String qrconnect_base_url = "https://open.weixin.qq.com/connect/qrconnect";
            String url = qrconnect_base_url + "?appid=" + appId + "&redirect_uri=" + URLEncoder.encode(weChatRootUrl + WX_CALL_PATH, StandardCharsets.UTF_8.name());
            url += "&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
            log.info("生成的地址={}", url);
            return Result.success(url);
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    @ApiImplicitParam("微信扫码登录,前端获取微信的code,后台通过code拿到用户信息")
    @RequestMapping(WX_CALL_PATH)
    public Result wxCall(String code) {
        //1获取openid
        try {
            WxMaJscode2SessionResult res = wxMaService.jsCode2SessionInfo(code);

            String openid = res.getOpenid();
            String sessionKey = res.getSessionKey();
            String unionid = res.getUnionid();
            return Result.success(null);
        } catch (WxErrorException e) {
            return Result.failure(e.getMessage());
        }
    }

}
